<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/25 0025
 * Time: 下午 7:02
 */
namespace App\GameService;

use App\WebSocket\WsBase;
use App\Common\AuthCommon;
use App\Utility\BaseEnum;
use App\GameService\tasks\MoveClientTask;
use EasySwoole\FastCache\Cache;
use EasySwoole\EasySwoole\Task\TaskManager;
use App\Enum\SysEnum;

/**
 * 玩家登录操作
 *
 * @author Administrator
 *        
 */
class Guser extends WsBase
{

    /**
     * TODO 登录验证TOKEN的数据
     * TODO 进入WEB地址：
     * URL：http://play.games.top:7456?account=10015_player001&token=5++bB+VCHTlTsZt9Cw1vDdHfz3kvfEgsqPvfWWqHVp0snHYEyMinH7QEl7yhQMgVHnhokII/iW3WkOaQ1LhoUw==&Gid=0 
     */
    public function login() {
        $error = '';
        $data = $this->paramsBean->getData(true);
        $loginFd = $this->paramsBean->getFd();
        BaseEnum::Logger('登录用户: Data：' . json_encode($data), 'user-login');
        //执行登录功能；
        $userName = isset($data['account']) ? $data['account'] : "" ;       //玩家名称；
        $userParams = isset($data['subdata']) ? $data['subdata'] : "" ;     //玩家身份信息验证参数
        $userTokenStr = !empty($userParams) ? rawurldecode($userParams): $userParams;  //URL获取参数进行URL地址解码
        
        //缓存值
        //Cache::getInstance()->set('temp_data',$data);
        //var_dump(Cache::getInstance()->get('temp_data'));
        try {
            if($userName && !empty($userParams)){
                $loginUser = FALSE ;//登录换新的验证：
                if(!empty($userTokenStr) && substr($userTokenStr, -2) != "==") {  $userTokenStr .= "==";}
                if($userTokenStr == 'cHdkOmFiYzEyMw=='){
                    $loginUser = AuthCommon::loginIntoGame($userName,$userTokenStr,$loginFd,$error);
                }else{
                    $loginUser = AuthCommon::loginWSGames($userName,$userTokenStr,$loginFd,$error);
                }
                $loginUid = isset($loginUser['uid']) ? intval($loginUser['uid']): 0; 
                if(!$loginUser || !$loginUid){
                    $error = !empty($error) ? $error : BaseEnum::MSG_0XF1;
                    $this-> ResError($error , "登录失败",SysEnum::RETURN_MSG_LEVEL_3);
                }else{
                    //TODO 标识登录成功 =====>  标识当前玩家的登录状态为在线。
                    AuthCommon::LoginOKServer($loginUid,$loginFd); 
                    $loginUser['uid']=$loginUid;
                    $this->ResOK($loginUser, "登录成功");
                }
            }else {
                $this-> ResError(BaseEnum::MSG_0XF1,"登录参数丢失",SysEnum::RETURN_MSG_LEVEL_3);
            }
        } catch (\Throwable $e) {
            BaseEnum::Logger($e->getMessage(), 'user-login');
            return FALSE;
        }
        return TRUE;
    }
    
    
    /**
     * 登出下线
     */
    public function loginout() {
        $error = '';
        $data = $this->paramsBean->getData(true);
        $loginFd = $this->paramsBean->getFd();
        BaseEnum::Logger('登出用户：Request Data：' . json_encode($data), 'user-login');
        try {
            if($loginFd){
                $res = AuthCommon::clearLoginFd($loginFd);
                $this->ResOK(1,"登出成功");
            }else {
                $this-> ResError(-1,"系统异常");
            }
        } catch (\Throwable $e) {
            BaseEnum::Logger($e->getMessage(), 'user-login');
            return FALSE;
        }
        return TRUE;
    }
    
    
    
    

    /**
     * 登录用户信息获取
     *
     * @return boolean
     */
    public function getUser()
    {
        try {
            // 获取参数内容
            $params = $this->paramsBean->getData();
            $loginFd = $this->paramsBean->getFd()  ; //登录的FD信息
            
            //登录用户信息获取
            $loginUser = AuthCommon::getLoginUser($loginFd,$error);
            if(!$loginUser){
                $this-> ResError(-1 , $error ?? "获取失败");
            }else{
                $this->ResOK($loginUser, "获取用户信息成功");
            }
        } catch (\Throwable $e) {
            BaseEnum::Logger($e->getMessage(), 'user-login');
            return false;
        }
        return true;
    }

    /**
     * 通知用户上线
     * WEBSOCKET_STATUS_CONNECTION = 1，连接进入等待握手
     * WEBSOCKET_STATUS_HANDSHAKE = 2， 正在握手
     * WEBSOCKET_STATUS_FRAME = 3， 已握手成功等待浏览器发送数据帧
     *
     * @return boolean
     */
    public function noticeUser()
    {
        try {
            // 获取参数内容
            $params = $this->paramsBean->getData();
            $reqData = ! empty($params) ? json_decode($params, true) : false;
            BaseEnum::Logger('通知用户上线：Request $params ：' . json_encode($params), 'user-login');
            $userfd = isset($reqData['fd']) ? $reqData['fd'] : 0;
            $playerName = isset($reqData['token']) ? $reqData['token'] : '';
            if (! $userfd) {
                $this->ResError(- 1, "没有用户FD，推送无效");
                return false;
            }

            // 获取FD的状态信息；
            $info = ServerManager::getInstance()->getServer()->connection_info($userfd);
            // 调用；
            $userOk = [
                'uid' => 1001,
                'agentId' => $userfd,
                "name" => 'test002**',
                "status" => 0,
                "points" => 200,
                'token' => $playerName,
                "fdinfo" => $info
            ];

            // 是否握手成功
            if (isset($info['websocket_status']) && intval($info['websocket_status']) !== WEBSOCKET_STATUS_FRAME) {
                $this->ResError(- 1, "目录FD不在线，推送将发送失败");
                return false;
            }
            $responseJson = json_encode([
                "msg" => "推送信息内容",
                "code" => 200,
                "token" => $playerName
            ]);

            // 推送到指定用户
            ServerManager::getInstance()->getServer()->push($userfd, $responseJson);
            $this->ResOK($userOk); // 执行登录功能；
            return true;
        } catch (\Throwable $e) {
            BaseEnum::Logger($e->getMessage(), 'user-login');
            return false;
        }
        BaseEnum::Logger('--Guser-(noticeUser)-End--', 'user-login');
        return false;
    }

    /**
     * 只给当前建立连接的推送
     */
    public function openPrize()
    {
        // 推送多个信息,不存储信息
        TaskManager::getInstance()->async(function () {
            try {
                // BaseEnum::Logger('--lottery-openPrize-start--', 'lottery_socket');
                $platCode = $this->paramsBean->getPlatCode();
                $pushType = $this->paramsBean->getPushType();
                $data = $this->paramsBean->getData();
                // BaseEnum::Logger('Receive Data:'.json_encode($data), 'lottery_socket');

                // 获取当前平台下存储的所有的Fd
                $platFds = PlatsService::getAllFds($platCode, $pushType);
                // BaseEnum::Logger('Current Plat Fds:'.$platCode.'-'.$pushType.'=>'.json_encode($platFds), 'lottery_socket');
                // 当前平台下面没有链接的
                if (! $platFds)
                    return false;

                foreach ($platFds as $fd) {
                    $exceptions = new Exceptions();
                    $exceptions->setStatus(ResponseEnum::OPEN_PRIZE_SUCCESS_STATUS);
                    $exceptions->setCode(ResponseEnum::OPEN_PRIZE_SUCCESS_CODE);
                    $exceptions->setMsg(ResponseEnum::OPEN_PRIZE_SUCCESS_MSG);
                    $exceptions->setData($data);
                    $responseJson = $exceptions->responseJson();
                    // BaseEnum::Logger('Push Data:'.$fd.'==>'.$responseJson, 'lottery_socket');
                    $info = ServerManager::getInstance()->getServer()->connection_info($fd);
                    if (! is_array($info) || ! $info['websocket_status'])
                        continue;
                    $result = ServerManager::getInstance()->getServer()->push($fd, $responseJson);
                    // $pushResult = isset($result) && $result ? 'true' : 'false';
                    // BaseEnum::Logger('Push Result:'.$fd.'==>'.$pushResult, 'lottery_socket');
                    if ($result)
                        continue;
                    $close = new OnClose($fd);
                    $close->destroy();
                }
                // BaseEnum::Logger('---------------lottery-openPrize-end---------------', 'lottery_socket');
                return true;
            } catch (\Throwable $e) {
                // print_r($e->getMessage());
                // BaseEnum::Logger('---------------lottery-openPrize-err----------------', 'lottery_socket');
                BaseEnum::Logger($e->getMessage(), 'lottery_socket');
                // BaseEnum::Logger('---------------lottery-openPrize-err----------------', 'lottery_socket');
                return false;
            }
        });
    }
}